import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { DialogQueue } from '@/utils/dialogQueue'
import { agencyAsync } from '@/appox/appox'
import { appoxEnums } from '@/appox/appox'

export const usePluginLibraryStore = defineStore('pluginLibrary', () => {
  // 状态
  const dialogQueue = new DialogQueue()
  const searchKey = ref('')
  const pluginInfoTable = ref(new Map())
  const selectedPluginId = ref('')
  const enableCheck = ref(false)

  // 计算属性
  const filteredPlugins = computed(() => {
    const key = searchKey.value.toLowerCase()
    return Array.from(pluginInfoTable.value.values())
      .filter(info => isPluginInfoHit(info, key))
      .sort((a, b) => a.name.localeCompare(b.name))
  })

  const selectedPlugin = computed(() => {
    return pluginInfoTable.value.get(selectedPluginId.value)
  })

  function isPluginPackOK(plugin) {
    return plugin && plugin.error === appoxEnums.PluginPackError.OK
  }

  // 辅助函数
  function isPluginInfoHit(info, key) {
    return info.id.toLowerCase().includes(key) ||
           info.name.toLowerCase().includes(key) ||
           info.brief.toLowerCase().includes(key) ||
           info.appLayerDetails.toLowerCase().includes(key) ||
           info.nativeLayerDetails.toLowerCase().includes(key)
  }

  // 动作
  async function initialize() {
    try {
      pluginInfoTable.value.clear()
      const idList = await agencyAsync.getPluginPackIDList()
      
      if (!idList || !Array.isArray(idList)) {
        return
      }
      
      if (idList.length === 0) {
        return
      }

      const infoPromises = idList.map(id => 
        agencyAsync.getPluginPackInfo(id).then(info => [id, info])
      )
      
      const infoResults = await Promise.all(infoPromises)
      for (const [id, info] of infoResults) {
        if (info) {
          pluginInfoTable.value.set(id, info)
        }
      }
    } catch (error) {
      // 静默处理错误
    }
  }

  async function updateSinglePluginInfo(pluginId) {
    const info = await agencyAsync.getPluginPackInfo(pluginId)
    pluginInfoTable.value.set(pluginId, info)
    return info
  }

  function selectPlugin(pluginId) {
    selectedPluginId.value = pluginId
    const info = pluginInfoTable.value.get(pluginId)
    if (info) {
      enableCheck.value = info.status !== appoxEnums.PluginPackStatus.Disabled
    }
  }

  async function togglePluginStatus() {
    const info = pluginInfoTable.value.get(selectedPluginId.value)
    if (!info) return

    if (enableCheck.value) {
      if (info.status === appoxEnums.PluginPackStatus.Disabled) {
        await agencyAsync.enablePlugin(selectedPluginId.value)
      }
    } else {
      if (info.status !== appoxEnums.PluginPackStatus.Disabled) {
        await agencyAsync.disablePlugin(selectedPluginId.value)
      }
    }

    await updateSinglePluginInfo(selectedPluginId.value)
  }

  function show() {
    return dialogQueue.show({
      onLoaded: () => initialize()
    })
  }

  function hide() {
    dialogQueue.hide()
  }

  return {
    // 状态
    isVisible: dialogQueue.isVisible,
    searchKey,
    pluginInfoTable,
    selectedPluginId,
    enableCheck,
    // 计算属性
    filteredPlugins,
    selectedPlugin,
    isPluginPackOK,
    // 动作
    initialize,
    selectPlugin,
    togglePluginStatus,
    show,
    hide,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
}) 